from fastapi import APIRouter, Depends, Form, HTTPException
from sqlalchemy.orm import Session
import models
from schemas import DictionaryAdd
from db import get_db

router = APIRouter(prefix="/api/dictionary", tags=["词典"])




@router.put("/update/{id}")
def update_dictionary(id: int, data: DictionaryAdd, db: Session = Depends(get_db)):
    dictionary_item = db.query(models.dictionary).filter(models.dictionary.id == id).first()
    if not dictionary_item:
        raise HTTPException(status_code=404, detail="字典项未找到")
    existing_en = db.query(models.dictionary).filter(models.dictionary.EN == data.EN, models.dictionary.id != id).first()
    if existing_en:
        raise HTTPException(status_code=400, detail="单词已添加")
    existing_zh = db.query(models.dictionary).filter(models.dictionary.ZH == data.ZH, models.dictionary.id != id).first()
    if existing_zh:
        raise HTTPException(status_code=400, detail="单词已添加")
    existing_uy = db.query(models.dictionary).filter(models.dictionary.UY == data.UY, models.dictionary.id != id).first()
    if existing_uy:
        raise HTTPException(status_code=400, detail="单词已添加")
    dictionary_item.EN = data.EN
    dictionary_item.ZH = data.ZH
    dictionary_item.UY = data.UY
    db.commit()
    db.refresh(dictionary_item)
    return dictionary_item
